<template>
  <div class="editUserInfo">
    <hmheader title='个人信息编辑'>
      <!-- slot:指定内容放置到那个插槽中 -->
      <span class="iconfont iconjiantou2"
            slot='left'
            @click="$router.back()"></span>
      <span slot='right'
            class="van-icon van-icon-wap-home-o"
            style='font-size:20px;color:Red'
            @click='$router.push({name:"index"})'></span>
    </hmheader>
    <div class="userimg">
      <img alt=""
           :src="current.head_img">
      <!-- 文件上传组件 -->
      <van-uploader :after-read="afterRead" />
    </div>
    <hmcell title='昵称'
            :desc='current.nickname'
            @click='nickshow = !nickshow'></hmcell>
    <van-dialog v-model="nickshow"
                title="编辑昵称"
                show-cancel-button
                @confirm='updateNickname'
                @cancel='editvalue.nickname = current.nickname'>
      <van-field v-model="editvalue.nickname"
                 required
                 label="昵称"
                 placeholder="请输入昵称" />
    </van-dialog>
    <hmcell title='密码'
            desc='*******'
            @click='passshow = !passshow'></hmcell>
    <van-dialog v-model="passshow"
                title="修改密码"
                show-cancel-button
                @cancel='editvalue.originpass=editvalue.newpass=""'
                @confirm='updatePass'
                :before-close='beforeClose'>
      <van-field placeholder="请输入原密码"
                 required
                 v-model="editvalue.originpass"
                 label="原密码" />
      <van-field placeholder="请输入新密码"
                 required
                 v-model="editvalue.newpass"
                 label="新密码" />
    </van-dialog>
    <hmcell title='性别 '
            :desc="current.gender==1?'男':'女'"
            @click='gendershow = !gendershow'></hmcell>
    <van-action-sheet v-model="gendershow"
                      :actions="[{name:'女'},{name:'男'}]"
                      @select="onSelect" />
  </div>
</template>

<script>
import hmheader from '@/components/hmheader.vue'
import hmcell from '@/components/hmcell.vue'
import { uploadFile } from '@/apis/upload.js'
import { getUserInfo, updateUserInfo } from '@/apis/user.js'
import axios from '@/utils/myaxios.js'
export default {
  components: {
    hmheader, hmcell
  },
  data () {
    return {
      current: {},
      editvalue: {
        originpass: '', // 原密码
        newpass: '' // 用户输入的密码
      },
      nickshow: false,
      passshow: false,
      gendershow: false
    }
  },
  methods: {
    async onSelect (item) {
      console.log(item);
      let res = await updateUserInfo(this.current.id, { gender: item.name == '男' ? 1 : 0 })
      // 实现页面刷新
      this.current.gender = item.name == '男' ? 1 : 0
      this.$toast.success('用户性别修改成功')
      this.gendershow = false
    },
    // 文件上传及头像编辑
    async afterRead (myfile) {
      // 此时可以自行将文件上传至服务器
      // 收集文件数据
      let formdata = new FormData()
      formdata.append('file', myfile.file)
      // 1.实现文件上传
      let res = await uploadFile(formdata)
      // 下面这句本质上实现了页面的刷新
      this.current.head_img = axios.defaults.baseURL + res.data.data.url
      if (res.data.message == '文件上传成功') {
        // 2.编辑用户头像
        let res2 = await updateUserInfo(this.current.id, { head_img: res.data.data.url })
        this.$toast.success('用户头像修改成功')
      }
    },
    // 编辑昵称
    async updateNickname () {
      let res = await updateUserInfo(this.current.id, { nickname: this.editvalue.nickname })
      this.current.nickname = this.editvalue.nickname
      this.$toast.success('用户昵称修改成功')
      console.log(res);
    },
    // 修改密码
    async updatePass () {
      let userobj = JSON.parse(localStorage.getItem('toutiao_59_userinfo'))
      // 判断 原密码是否匹配
      if (this.editvalue.originpass == userobj.password) {
        // 新密码需要进行验证
        if (/^.{3,}$/.test(this.editvalue.newpass)) { // 用户输入的新密码通过验证
          // 修改密码
          let res = await updateUserInfo(this.current.id, { password: this.editvalue.newpass })
          this.$toast.success('用户密码修改成功')
          // 更新数据
          userobj.password = this.editvalue.newpass
          // 重新存储
          localStorage.setItem('toutiao_59_userinfo', JSON.stringify(userobj))
          // 清空
          this.editvalue.originpass = this.editvalue.newpass = ''
        } else {
          this.$toast.fail('请输入3位及以上的新密码')
        }
      } else {
        this.$toast.fail('原密码输入不正确')
      }
    },
    // 添加用户体验，阻止模态框的关闭
    beforeClose (action, done) {
      // 点击确认
      if (action == 'confirm') {
        let userobj = JSON.parse(localStorage.getItem('toutiao_59_userinfo'))
        // 判断 原密码是否匹配
        if (this.editvalue.originpass != userobj.password) {
          done(false)
        } else {
          if (!/^.{3,}$/.test(this.editvalue.newpass)) {
            done(false)
          } else {
            done()
          }
        }
      } else { // 点击取消
        done()
      }
    }
  },
  async mounted () {
    let res = await getUserInfo(this.$route.params.id)
    console.log(res);
    if (res.data.message == '获取成功') {
      res.data.data.head_img = axios.defaults.baseURL + res.data.data.head_img
      this.current = res.data.data
      // 仅仅是方便我们编辑时的数据展示和数据获取
      this.editvalue.nickname = this.current.nickname
      console.log(this.editvalue);
    }
  }
}
</script>

<style lang="less" scoped>
.userimg {
  padding: 30px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  img {
    width: 100 / 360 * 100vw;
    height: 100 / 360 * 100vw;
    border-radius: 50%;
  }

  /deep/ .van-uploader {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    opacity: 0;
  }
  /deep/ .van-uploader__upload {
    width: 100 / 360 * 100vw;
    height: 100 / 360 * 100vw;
    margin: 0;
  }
}
</style>